import $http from './request.js'
import {
  getUserInfo,
  getAutoCompanyCert,
  getVipRecord
} from '@/common/api/user'
import {
  wxMpTokenDecrypt,
  isNeedSetPassword,
  getMenu,
  bindWechat,
  appLogin
} from '@/passport/api'
import { redirectLoginSuccess } from './passport'
import store from '@/store'
import { toast, jump, loading } from '@/common/util'

export default {
  refreshToken: '',
  // 手机号+密码或手机号+手机验证码登录
  async login(url, data) {
    const l = loading('登录中...')
    this.removeLoginInfo()
    const [err, res] = await $http.post(url, data, {
      noCheck: true
    })
    l.hide()
    if (!$http.errorCheck(err, res)) return false

    if (res.data.accountStatus == 1) {
      return this.checkLogOut(data, res.data)
    } else if (res.data.accountStatus == 2) {
      toast('该账号已注销，无法继续使用')
      return false
    } else {
      // 保存状态
      this.saveLoginInfo(res)
      await this.getVipRecord()
      await this.identityUser(url)
      return true
    }
  },

  // app一键登录
  async appPhoneLogin(data) {
    const [err, res] = await appLogin({
      token: data.access_token,
      openId: data.openid,
      identityTypes: 'autoCompany',
      loginType: 'app'
    })
    uni.closeAuthView()
    if (!$http.errorCheck(err, res)) return false

    if (res.data.accountStatus == 1) {
      return this.checkLogOut(data, res.data)
    } else if (res.data.accountStatus == 2) {
      toast('该账号已注销，无法继续使用')
      return false
    } else {
      // 保存状态
      this.saveLoginInfo(res)
      await this.getVipRecord()
      await this.identityUser('code')
      return true
    }
  },

  // 登录成功 保存状态
  saveLoginInfo(res) {
	  console.log('2222222')
    const data = res.data
    const current = new Date()
    current.setTime(current.getTime() + data.expires_in * 1000)
    const expiresIn = current.getTime()
	store.commit('vehicle/setMaterialpromptShow',true)
    // 本地存储
    store.commit('user/setToken', data.access_token)
    store.commit('user/setUserId', data.userId)
    store.commit('user/setExpiresIn', expiresIn)
    store.commit('status/setFirstLogin', true)
    store.commit('status/setFirstShowModel', true)
  },

  // 获取用户信息
  async getUserInfo() {
    const [err, res] = await getUserInfo()
    if (!$http.errorCheck(err, res)) return false
    const data = res.data.data
    const userInfo = data.sysUser
    store.commit('user/setUserInfo', userInfo)
    store.commit('user/setAuth', data.permissions)
  },

  // 获取会员信息
  async getVipRecord() {
    await this.getUserInfo()
    await this.getMenu()
    const [err, res] = await getVipRecord()
    if (!$http.errorCheck(err, res)) return false
    const data = res.data.data
    if (data[0]) store.commit('user/setVipInfo', data[0])
    else {
      store.commit('user/setVipInfo', {
        expirationDate: '',
        name: '免费版',
        vipServiceInfoId: ''
      })
    }
  },

  // 获取菜单
  async getMenu() {
    const [err, res] = await getMenu()
    store.commit('user/setMenu', res.data)
  },

  // 验证是否有登录密码
  async identityUser(url) {
    if (url && url.includes('code')) {
      // 如果是验证码登录判断是否有密码
      const [err, res] = await isNeedSetPassword()
      if (!$http.errorCheck(err, res)) return false
      if (res.data.data) {
        // 未设置密码跳转设置密码页面
        jump('/passport/forget-password/forget-password?type=1', 'reLaunch')
      } else {
        // 否则检查身份
        await this.checkIdentity()
      }
    } else {
      // 否则直接检查身份
      await this.checkIdentity()
    }
  },

  // 用户身份鉴定
  async checkIdentity() {
    const userInfo = store.getters.userInfo
    // 身份验证
    if (userInfo.certTypeLabel === 'personal') {
      // 如果用旅行社账号登录则返回个人身份
      // 旅行社账号登录change
      jump('/passport/cert/cert?type=1')
    } else {
      // 否则返回车企身份
      await this.getAutoCompanyCert()
    }
  },

  // 检测用户是否认证
  async getAutoCompanyCert() {
    const userInfo = store.getters.userInfo
    const userId = store.getters.userId
    if ((userInfo.certType.indexOf('20') != -1 || userInfo.certType.indexOf('21') != -1) && userInfo.certTypeLabel === 'autoCompany') {
      const data = { userId }
      // 查看车企认证资料
      const [err, res] = await getAutoCompanyCert(userId, data)
      if (!$http.errorCheck(err, res)) return false
      const certStatus = res.data.data.certStatus
      if (certStatus == 1) {
        redirectLoginSuccess()
      } else {
        // 认证change
        jump('/passport/cert/cert')
      }
    } else {
      redirectLoginSuccess()
    }
  },

  // 退出登录
  async loginOut(url) {
    loading('注销中...')
    const data = {
      accesstoken: store.getters.token
    }
    const [err, res] = await $http.post(url, data)
    if (!$http.errorCheck(err, res)) return false
    this.removeLoginInfo()
    toast('退出登录成功', () => {
      jump('/passport/login/login', 'reLaunch')
    })
  },

  // 清除状态
  removeLoginInfo() {
    const expiresIn = new Date().getTime()
    store.commit('user/setToken', '')
    store.commit('user/setUserId', '')
    store.commit('user/setUserInfo', null)
    store.commit('user/setAuth', '')
    store.commit('user/setVipInfo', {})
    store.commit('user/setMenu', [])
    store.commit('user/setExpiresIn', expiresIn)
  },

  // APP微信登录绑定手机
  async thirdLoginBindAccount(data) {
    const [err, res] = await bindWechat(data)
    if (!$http.errorCheck(err, res)) return false
    // 登录成功 保存状态
    this.saveLoginInfo(res)
    await this.getVipRecord()
    await this.identityUser()
    return true
  },

  // 微信小程序微信登录
  async bindWechatPhone(data) {
    const load = loading('登录中...')
    const [err, res] = await wxMpTokenDecrypt(data)
    if (!$http.errorCheck(err, res)) return false
    if (res.data.accountStatus == 1) {
      load.hide()
      return this.checkLogOut(res.data)
    } else if (res.data.accountStatus === 2) {
      toast('该账号已注销，无法继续使用')
      return false
    } else {
      // 登录成功 保存状态
      this.saveLoginInfo(res)
      await this.getVipRecord()
      await this.identityUser()
      return true
    }
  },

  // 检查是否绑定
  async checkBind(url, data) {
    const [err, res] = await $http.post(url, data, {
      noCheck: true
    })
    if (!$http.errorCheck(err, res)) return false
    return true
  },

  // APP第三方登录
  async thirdLogin(url, datas) {
    const [err, res] = await $http.post(url, datas, {
      noCheck: true
    })
    if (!$http.errorCheck(err, res)) return false
    const data = res.data
    if (res.data.accountStatus == 1) {
      return this.checkLogOut(res.data)
    } else if (res.data.accountStatus === 2) {
      toast('该账号已注销，无法继续使用')
      return false
    }

    if (data.code == 668) {
      const data = res.data.data
      store.commit('user/setAppInfo', {
        providerId: data.providerId,
        providerUserId: data.providerUserId,
        sessionKey: data.sessionKey
      })

      toast('请绑定手机号', () => {
        // 绑定手机号 change
        jump('/passport/mobile/modify/index?type=1')
      })
      return false
    }

    // 登录成功 保存状态
    this.saveLoginInfo(res)
    await this.getVipRecord()
    const type = uni.getStorageSync('tbbLoginType')
    if (!type) await this.identityUser()
    else await this.checkIdentity()
    return true
  },

  // 注销验证
  checkLogOut(data, res) {
    let phone = ''
    const userId = data.userId || res.userId
    store.commit('user/setUserId', userId)
    if (data.phone) {
      phone = data.phone.substring(0, 3) + '****' + data.phone.substring(7, 11)
    }
    return phone
  }

}
